import React, { PropsWithChildren, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { CombinedState } from '../../store/reducers';
import { ProfilState } from '../../store/reducers/profile';
import actions from '../../store/actions/profile';
import LOGIN_TYPES from '../../typings/login-types';
import { RouteComponentProps } from 'react-router';
import { Descriptions, Button, Alert, message, Upload } from 'antd';
import NavHeader from '../../components/NavHeader';
import { AxiosError } from 'axios';
import './index.less';
import { LoadingOutlined, UpCircleOutlined } from '@ant-design/icons';

let mapStateToProps = (state: CombinedState): ProfilState => state.profile;
// 当前的组件有三个属性来源
// 1.mapStateToProps的返回值 2.actions对象类型 3.来自路由 4.用户传入进来的其他属性
type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof actions;
interface Params {}
type RouteProps = RouteComponentProps<Params>;
type Props = PropsWithChildren<StateProps & DispatchProps & RouteProps>;

function beforeUpload(file:any){
  const isJpgOrPng=file.type==='image/jepg' || file.type === 'image/png';
  if(!isJpgOrPng){
    message.error('你只能上传JPG/PNG文件！');
  }
  const isLessThan2M=file.size/1024/1024<2;
  if(!isLessThan2M){
    message.error('图片必须小于2MB！')
  }
  return isJpgOrPng && isLessThan2M;
}

function Profile(props: Props) {
  let [loading, setLoading] = useState(false);
  // 组件加载后直接发起验证请求，查看此用户是否已经登录过，如果没登录则提示错误
  useEffect(() => {
    props.validate().catch((error: AxiosError) => message.error(error.message));
  }, []);
  const handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
    } else if (info.file.status === 'done') {
      let { success, data, message } = info.file.response;
      if (success) {
        setLoading(false);
        props.changeAvatar(data);
      } else {
        message.error(message);
      }
    }
  };
  let content;
  if (props.loginState == LOGIN_TYPES.UN_VALIDATE) {
    content = null; // 验证失败内容为null
  } else if (props.loginState == LOGIN_TYPES.LOGINED) {
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <UpCircleOutlined />}
        <div className="ant-upload-text">上传</div>
      </div>
    );

    content = ( // 已登录显示用户信息
      <div className="user-info">
        <Descriptions title="当前登录用户">
          <Descriptions.Item label="用户名">
            {props.user.username}
          </Descriptions.Item>
          <Descriptions.Item label="手机号">15718856132</Descriptions.Item>
          <Descriptions.Item label="邮箱">{props.user.email}</Descriptions.Item>
          <Descriptions.Item label="头像">
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://localhost:8000/user/uploadAvatar"
              beforeUpload={beforeUpload}
              data={{ userId: props.user.id }}
              onChange={handleChange}
            >
              {props.user.avatar ? (
                <img
                  src={props.user.avatar}
                  alt="avatar"
                  style={{ width: '100%' }}
                />
              ) : (
                uploadButton
              )}
            </Upload>
          </Descriptions.Item>
        </Descriptions>
        <Button
          type="primary"
          onClick={async () => {
            await props.logout();
            props.history.push('/login');
          }}
        >
          退出登录
        </Button>
      </div>
    );
  } else {
    // 没登录，则显示登录和注册按钮
    content = (
      <>
        <Alert
          type="warning"
          message="当前未登录"
          description="亲爱的用户你好，你当前尚未登录，请你选择注册或者登录"
        />
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Button type="dashed" onClick={() => props.history.push('/login')}>
            登录
          </Button>
          <Button
            type="dashed"
            style={{ marginLeft: '50px' }}
            onClick={() => props.history.push('/register')}
          >
            注册
          </Button>
        </div>
      </>
    );
  }
  return (
    <section>
      <NavHeader history={props.history}>个人中心</NavHeader>
      {content}
    </section>
  );
}


export default connect(mapStateToProps, actions)(Profile);
